package com.itrui.order.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itrui.feign.client.ProductClient;
import com.itrui.feign.client.pojo.Product;
import com.itrui.order.common.Code;
import com.itrui.order.common.Result;
import com.itrui.order.pojo.ShoppingCart;
import com.itrui.order.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private ProductClient productClient;

    @PostMapping()
    public Result addCart(@RequestBody ShoppingCart cart){
        cart.setCreateTime(LocalDateTime.now());
        boolean save = shoppingCartService.save(cart);
        return new Result(save? Code.SAVE_OK:Code.SAVE_ERR,save?"添加成功":"添加失败");
    }

    @GetMapping("/{id}")
    public Result getCart(@PathVariable Long uid){
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, uid);
        ShoppingCart one = shoppingCartService.getOne(queryWrapper);
        Product productById = productClient.getProductById(one.getProductId());
        one.setProduct(productById);

        return new Result(Code.GET_OK,one,"查询成功");
    }

    @DeleteMapping()
    public Result deleteCart(@RequestParam List<Long> ids){
        boolean b = shoppingCartService.removeByIds(ids);
        return new Result(b?Code.DELETE_OK:Code.DELETE_ERR,b?"删除成功":"删除失败");
    }

}
